package com.gzx.plugin.tjzy.modular.qianwen.util;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.gzx.plugin.tjzy.modular.qianwen.constant.IntentType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Collections;

/**
 * 调用阿里通义千问模型demo
 */
@Slf4j
public class QwenClient {
    // 从环境变量读取API Key
    private static final String apiKey = "sk-07abcaa3f159434bb1caa8d83d3459c1";

    public static void main(String[] args) {
        try {
            String question = "卡牌的规则是什么";
            GenerationResult response = callQwen("你是一个卡牌游戏的NPC，我现在是卡牌的玩家，以下是我问你的问题：" + question, apiKey);
            if (ObjectUtils.isEmpty(response)) {
                log.error("系统异常请联系管理员：123@qq.com");
            }
            String content = response.getOutput().getChoices().getFirst().getMessage().getContent();
            log.info("AI回复：{}", content);
        } catch (Exception e) {
            log.error("调用失败：{}", e.getMessage());
        }
    }

    //调用模型
    public static GenerationResult callQwen(String prompt, String apiKey) throws NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(prompt)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                //apiKey配置到nacos里面
                .apiKey(apiKey)
                .model(IntentType.MODEL)
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
}
